package com.myway.service.ibe.command;

import com.myway.core.execption.IBEException;
import com.myway.dto.ibe_param.Ticket;
import com.myway.dto.ibe_param.TicketSegment;
import com.myway.dto.order.domain.PassengerType;
import com.travelsky.ibe.client.pnr.DETR;
import com.travelsky.ibe.client.pnr.DETRTKTResult;
import com.travelsky.ibe.client.pnr.DETRTKTSegment;
import com.travelsky.ibe.exceptions.DETRNonETPNRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 提取电子客票
 */
@Slf4j
public class RetrieveTicketCommand extends BaseIBECommand {

    /*@Autowired
    private PassengerSegmentDao passengerSegmentDao;
    @Autowired
    private PassengerDao passengerDao;
    @Autowired
    private FltChangeDao fltChangeDao;*/

    @SuppressWarnings("unchecked")
    public void execute(Map<String, Object> parms, String airline) {
        String PNRNo=(String)parms.get("PNRNo");
        DETR de=new DETR();
        List<Ticket> list=null;
        this.configIBEClient(de, airline);
        try {
            //客票信息
            //FIXME 按PNR生成客票号 测试环境（注释会影响测试出票流程）
//            if(!ContextConfig.isOnline){//测试环境
                /*list=new ArrayList<Ticket>();
                Map<String,Ticket> mapT=new HashMap<String, Ticket>();

                List<Passenger> passengers=passengerDao.findPassengerDetailByPnrNo(PNRNo);
                List<Passenger> passengers_notkt=passengerDao.findPassengerDetailByPnrNo(PNRNo,false);//没出票的旅客
                List<Passenger> passengers_tkt=passengerDao.findPassengerDetailByPnrNo(PNRNo,true);//出票的旅客
                List<PassengerSegment> pslist=new ArrayList<PassengerSegment>();
                //FIXME PNR提取客票 兼容改期升舱 测试环境
                List<FltChangePaxSeg> changePaxs=fltChangeDao.findFltChangePaxSegByNewPnr(PNRNo);
                if(!CollectionUtils.isEmpty(passengers_notkt)||!CollectionUtils.isEmpty(changePaxs)){//未出票
                    //passengerSegmentDao.findPassengerSegmentByPnrAndInventory(PNRNo, Inventory.IBE);
                    for(Passenger p:passengers_notkt){
                        for(PassengerSegment ps:p.getPassengerSegments()){
                            pslist.add(ps);
                        }
                    }
                    for(FltChangePaxSeg cps:changePaxs){
                        if(cps.getNewPaxSeg()!=null)pslist.add(cps.getNewPaxSeg());
                    }
                    for(PassengerSegment ps :pslist){

                        TicketSegment seg=new TicketSegment();
                        IBEPassenger pas=new IBEPassenger();
                        Segment s=ps.getSegment();
                        seg.setArrAirportCode(s.getArrCode());
                        seg.setCabin(s.getCabinClass().charAt(0));
                        seg.setDepAirportCode(s.getDepCode());
                        seg.setDepTime(s.getDepTime());
                        seg.setFlightNo(s.getFlightNo());
                        seg.setPnrNo(PNRNo);
                        seg.setTicketStatus(TicketStatus.OPEN_FOR_USE.getAlias());

                        Ticket ticket=new Ticket();
                        ticket.setPnrNo(PNRNo);
                        String paxName=ps.getPassenger().getCustomer().getName();
                        ticket.setPassengerName(paxName);
                        ticket.setTicketNo("811-"+NumberGenerator.generateRandomNumber(10));
                        ticket.getSegments().add(seg);
                        list.add(ticket);
                    }
                }else{
                    List<TicketSegment> segs=new ArrayList<TicketSegment>();
                    for(Passenger p:passengers){
                        p.getPassengerSegments().size();
                        for(PassengerSegment ps :p.getPassengerSegments()){
                            TicketSegment seg=new TicketSegment();
                            IBEPassenger pas=new IBEPassenger();
                            Segment s=ps.getSegment();
                            seg.setArrAirportCode(s.getArrCode());
                            seg.setCabin(s.getCabinClass().charAt(0));
                            seg.setDepAirportCode(s.getDepCode());
                            seg.setDepTime(s.getDepTime());
                            seg.setFlightNo(s.getFlightNo());
                            seg.setPnrNo(p.getPnr().getPnrNo());
                            seg.setTicketStatus(TicketStatus.OPEN_FOR_USE.getAlias());
                            String tickNo="";
//							if(ps.getTicket()==null){
//								tickNo="811-"+NumberGenerator.generateRandomNumber(10);
//							}else{
                            tickNo=ps.getTicket().getIssCode()+"-"+ps.getTicket().getTicketNo();
//							}
                            Ticket ticket=new Ticket();
                            ticket.setPnrNo(PNRNo);
                            if(mapT.get(tickNo)!=null){
                                ticket=mapT.get(tickNo);
                            }else{
                                String paxName=p.getCustomer().getName();
                                ticket.setPassengerName(paxName);
                                ticket.setPassengerType(p.getPassengerType().toString());
                                ticket.setCertificateNo(p.getCustomer().getCertificateNo());
                                ticket.setCertificateType(p.getCustomer().getCertificateType());
                                ticket.setTicketNo(tickNo);
                                ticket.setPnrNo(p.getPnr().getPnrNo());
                            }
                            ticket.getSegments().add(seg);
                            mapT.put(tickNo, ticket);
                        }
                        Iterator<Ticket> itks=mapT.values().iterator();
                        while(itks.hasNext()){
                            list.add(itks.next());
                        }
                    }
                }*/
//            }else if(ContextConfig.isOnline){//生产环境
                /**
                 * FIXME [IBE] 客票与航段绑定 生产环境
                 RT rt=new RT();
                 this.configIBEClient(rt, airline);
                 // 提取 PNR 信息 MTYJGS NFJBBN
                 RTResult rtres = rt. retrieve (PNRNo);
                 Vector tktnos = rtres.getTktnos();
                 DETR detr = new DETR();
                 this.configIBEClient(detr, airline);
                 for (Object object : tktnos) {
                 PNRTktNo tkt = (PNRTktNo)object;
                 DETRTKTResult result = detr.getTicketInfoByTktNo(tkt.getTktNo());
                 Ticket ticket=new Ticket();
                 ticket.setPassengerName(result.getPassengerName());
                 ticket.setTicketNo(result.getTicketNo());
                 for(int i=0;i<result.getSegmentCount();i++){
                 DETRTKTSegment segment=result.getSegment(i);
                 TicketSegment ticketSegment=new TicketSegment();
                 BeanUtils.copyProperties(segment, ticketSegment);
                 ticket.getSegments().add(ticketSegment);
                 }
                 list.add(ticket);
                 }
                 */
                list=new ArrayList<Ticket>();
                try {
//				FIXME [IBE] 获取客票信息 生产环境
                    Vector<DETRTKTResult> v = de.getTicketInfoByPNR(PNRNo);
                    if(null != v && v.size() > 0) {
                        for(DETRTKTResult result:v){
                            Ticket ticket=new Ticket();
                            ticket.setPassengerName(result.getPassengerName());
                            ticket.setConjunctionTkt(result.getFollowTicketNo());
                            if(result.getPassengerType()==DETRTKTResult.PASSENGER_ADULT){
                                ticket.setPassengerType(PassengerType.ADULT.getAlias());
                            }else if(result.getPassengerType()==DETRTKTResult.PASSENGER_CHILD){
                                ticket.setPassengerType(PassengerType.CHILD.getAlias());
                            }else if(result.getPassengerType()==DETRTKTResult.PASSENGER_INFANT){
                                ticket.setPassengerType(PassengerType.INFANT.getAlias());
                            }
                            ticket.setTicketNo(result.getTicketNo());
                            for(int i=0;i<result.getSegmentCount();i++){

                                DETRTKTSegment segment=result.getSegment(i);
                                TicketSegment ticketSegment=new TicketSegment();
                                BeanUtils.copyProperties(segment, ticketSegment);
                                ticket.getSegments().add(ticketSegment);
                            }
                            list.add(ticket);
                        }
                    }
                }catch(DETRNonETPNRException e) {
                    log.error("Caught DETRNonETPNRException");
                } catch (Exception e) {
                    //FIXME IBE提取客票异常判断为没有出票
                    log.error(e.getMessage(),e);
                }
//            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
            throw new IBEException(e.getMessage(),e);
        }
        parms.put("Ticket", list);
        //return list;

    }

}
